/*
 * MsgForm.java
 *
 * Created on May 15, 2008, 2:10 AM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */
package morseme;

/**
 *
 * @author tt
 */
import javax.microedition.lcdui.*;
import javax.wireless.messaging.*;
import java.util.*;

public class MsgForm extends Form implements CommandListener {

    private static final Command okCmd = new Command("OK", Command.OK, 0);
    private static final Command backCmd = new Command("Back", Command.BACK, 1);
    private static final Command playCmd = new Command("Play", Command.OK, 2);
    
    private Inbox inbox;
    private MorseME midlet;
    
    private StringItem usrLabel;
    private BlindTextField pwdField;
    private StringItem remainTime;
    
    private Form authenForm;
    
    private String username;
    private String password;
    private String content;
    private String morse;
    
    private Timer inputTimer;
    private TimerTask inputTimerTask;
    private int remainSec;
    private int wrongCount;
    
    private Message currentMsg;

    public MsgForm(Inbox inbox,MorseME midlet) {

        super("Message Detail");
        
        this.midlet = midlet;
        
        this.remainTime = new StringItem("","");
        this.usrLabel = new StringItem("Username:\n","");
        this.pwdField = new BlindTextField("Password:\n","",20,TextField.DECIMAL,this.midlet);
        
        this.authenForm = new Form("Authentication");
        this.authenForm.append(this.usrLabel);
        this.authenForm.append(this.pwdField);
        this.authenForm.append(this.remainTime);
        this.authenForm.addCommand(okCmd);
        this.authenForm.setCommandListener(this);
        
        this.inputTimer = new Timer();
        this.inbox = inbox;
        this.addCommand(backCmd);
        this.addCommand(playCmd);
        this.setCommandListener(this);
    }

    public void setMessage(Message rawMsg) {

        this.currentMsg = rawMsg;
        
        String addr = rawMsg.getAddress();
        Date date = rawMsg.getTimestamp();
        TextMessage tm = (TextMessage) rawMsg;
        String detail = tm.getPayloadText();
        
        String org = detail;
        String msg = detail;
        
        String leftString = null;
        
        this.username = msg.substring(0,msg.indexOf("#"));
        leftString = msg.substring(msg.indexOf("#")+1);
        this.password  = leftString.substring(0,leftString.indexOf("#"));
        this.content = leftString.substring(leftString.indexOf("#")+1);
        this.morse = MorseProcess.translate(content);
        
        this.deleteAll();
        
        this.append(new StringItem("From : ", formAddress(addr)));
        this.append(new StringItem("Time : ", date.toString()));
        
        if("none".equals(this.username) && "none".equals(this.password)){
            this.append(new StringItem("+SMS : ", content));
            this.append(new StringItem("+Morse : ", morse));
        }
    }

    private String formAddress(String addr) {
        return addr;
    }
    
    private void wrongExceeded(){
        this.inputTimerTask.cancel();
        
        this.usrLabel.setText("");
        this.pwdField.setString("");
        
        this.inbox.removeMessage(this.currentMsg);
        this.inbox.updateInbox();
        
        Display.getDisplay(this.midlet).setCurrent(this.inbox);
    }

    private void decreaseTime(){
        if(this.remainSec == 0){
            wrongExceeded();
        }
        
        this.remainTime.setText("Remain time: "+this.remainSec+" s.");
        this.remainSec--;
    }
    
    private void setAuthentication(){
        if("none".equals(this.username)){
            this.usrLabel.setText("[Not defined]");
        }else{
            this.usrLabel.setText(this.username);
        }
        this.pwdField.setString("");

        this.remainSec = 120;
        this.wrongCount = 3;
        
        this.inputTimerTask = new TimerTask(){
            public void run(){
                decreaseTime();
            }
        };
        this.inputTimer.scheduleAtFixedRate(inputTimerTask, 0, 1000);
        
        Display.getDisplay(this.midlet).setCurrent(this.authenForm);
    }
    
    private void authenSucceeded(){
        this.inputTimerTask.cancel();
        
        this.username = "none";
        this.password = "none";
        this.inbox.decryptMessage(this.currentMsg);
        this.inbox.updateInbox();

        this.append(new StringItem("+SMS : ", this.content));
        this.append(new StringItem("+Morse : ", this.morse));

        Display.getDisplay(this.midlet).setCurrent(this);
        this.midlet.play(this.morse);
    }
    
    public void commandAction(Command c, Displayable d) {
        if (c == backCmd) {

            this.inbox.updateInbox();
            Display.getDisplay(MorseME.getMIDlet()).setCurrent(this.inbox);

        } else if (c == playCmd) {
            if(!"none".equals(this.password)){
                
                setAuthentication();
                
            }else if (this.morse != null) {
                this.midlet.play(this.morse);
            }
        } else if(c == okCmd && d == this.authenForm) {
            
            if(this.password.equals(this.pwdField.getString())){
                
                authenSucceeded();
                
            }else{
                if(this.wrongCount == 0){
                    wrongExceeded();
                    return;
                }
                
                final int errorTone = 115;
                final int errorLong = 300;
                
                if(Option.VIBRATION_SEL == 0)
                    this.midlet.vibrate(errorLong);
                
                if(Option.SOUND_SEL == 0)
                    this.midlet.play(errorTone, errorLong);
                
                this.wrongCount--;
            }
            
            this.pwdField.setString("");
        }
    }
}

